package com.luom.fsp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luom.fsp.annotation.AuthCheck;
import com.luom.fsp.common.BaseResponse;
import com.luom.fsp.common.DeleteRequest;
import com.luom.fsp.common.ErrorCode;
import com.luom.fsp.common.ResultUtils;
import com.luom.fsp.constant.UserConstant;
import com.luom.fsp.exception.BusinessException;
import com.luom.fsp.exception.ThrowUtils;
import com.luom.fsp.model.dto.productReview.ProductReviewAddRequest;
import com.luom.fsp.model.dto.productReview.ProductReviewQueryByIdRequest;
import com.luom.fsp.model.dto.productReview.ProductReviewQueryRequest;
import com.luom.fsp.model.entity.ProductReview;
import com.luom.fsp.model.entity.User;
import com.luom.fsp.model.vo.ProductReviewVO;
import com.luom.fsp.service.ProductReviewService;
import com.luom.fsp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 商品评论接口
 *
*/
@RestController
@RequestMapping("/productReview")
@Slf4j
public class ProductReviewController {

    @Resource
    private ProductReviewService productReviewService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建商品评论
     *
     * @param productReviewAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addProductReview(@RequestBody ProductReviewAddRequest productReviewAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(productReviewAddRequest == null, ErrorCode.PARAMS_ERROR);
        ProductReview productReview = new ProductReview();
        BeanUtils.copyProperties(productReviewAddRequest, productReview);

        long newProductReviewId = productReviewService.addProductReview(productReview, request);
        return ResultUtils.success(newProductReviewId);
    }

    /**
     * 删除商品评论
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteProductReview(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        ProductReview oldProductReview = productReviewService.getById(id);
        ThrowUtils.throwIf(oldProductReview == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldProductReview.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = productReviewService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 商品id 获取商品评论（封装类）
     *
     */
    @PostMapping("/get/vo")
    public BaseResponse<List<ProductReviewVO>> getProductReviewVOById(
            @RequestBody ProductReviewQueryByIdRequest productReviewQueryRequest,
            HttpServletRequest request) {
        ThrowUtils.throwIf(productReviewQueryRequest == null, ErrorCode.PARAMS_ERROR);
        Long productId = productReviewQueryRequest.getProductId();
        int pageSize = productReviewQueryRequest.getPageSize();
        int current = productReviewQueryRequest.getCurrent();
        if (pageSize > 20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<ProductReview> page = productReviewService.page(new Page<>(current, pageSize),
                new QueryWrapper<ProductReview>()
                        .eq("productId", productId)
                        .orderByDesc("createTime")
        );
        return ResultUtils.success(productReviewService.getProductReviewVOPage(page, request).getRecords());
    }

    /**
     * 分页获取商品评论列表（仅管理员可用）
     *
     * @param productReviewQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ProductReview>> listProductReviewByPage(@RequestBody ProductReviewQueryRequest productReviewQueryRequest) {
        long current = productReviewQueryRequest.getCurrent();
        long size = productReviewQueryRequest.getPageSize();
        // 查询数据库
        Page<ProductReview> productReviewPage = productReviewService.page(new Page<>(current, size),
                productReviewService.getQueryWrapper(productReviewQueryRequest));
        return ResultUtils.success(productReviewPage);
    }

    /**
     * 分页获取商品评论列表（封装类）
     *
     * @param productReviewQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ProductReviewVO>> listProductReviewVOByPage(@RequestBody ProductReviewQueryRequest productReviewQueryRequest,
                                                               HttpServletRequest request) {
        long current = productReviewQueryRequest.getCurrent();
        long size = productReviewQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<ProductReview> productReviewPage = productReviewService.page(new Page<>(current, size),
                productReviewService.getQueryWrapper(productReviewQueryRequest));
        // 获取封装类
        return ResultUtils.success(productReviewService.getProductReviewVOPage(productReviewPage, request));
    }

    /**
     * 分页获取当前登录用户创建的商品评论列表
     *
     * @param productReviewQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ProductReviewVO>> listMyProductReviewVOByPage(@RequestBody ProductReviewQueryRequest productReviewQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(productReviewQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        productReviewQueryRequest.setUserId(loginUser.getId());
        long current = productReviewQueryRequest.getCurrent();
        long size = productReviewQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<ProductReview> productReviewPage = productReviewService.page(new Page<>(current, size),
                productReviewService.getQueryWrapper(productReviewQueryRequest));
        // 获取封装类
        return ResultUtils.success(productReviewService.getProductReviewVOPage(productReviewPage, request));
    }

    // endregion
}
